package com.cs2340.practice;

import java.util.ArrayList;
import java.util.Scanner;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * @author Jasmine lawrence This class is the interface between the controller
 *         and the database
 * 
 */
public class TaskDataBaseAdapter {

	// Columns
	public static final String KEY_NAME = "Task_name";
	public static final String KEY_DESCRIPTION = "description";
	public static final String KEY_DUE_DATE = "due_date";
	public static final String KEY_DUE_TIME = "due_time";
	public static final String KEY_LOCATION = "location";
	public static final String KEY_CATEGORY = "category";
	public static final String KEY_USER = "user";
	public static final String KEY_COMPLETED = "completed";

	public static final String KEY_TASK = "tasks";
	public static final String KEY_ID = "_id";

	private static final String DATABASE_NAME = "TASK_DATABASE";
	private static final String DATABASE_TABLE = "TASK_TABLE";
	private static final int DATABASE_VERSION = 2;

	private String TAG = "task database";

	private DbHelper ourHelper;
	private final Context ourContext;
	private SQLiteDatabase ourDatabase;

	public static class DbHelper extends SQLiteOpenHelper {

		public DbHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * android.database.sqlite.SQLiteOpenHelper#onCreate(android.database
		 * .sqlite.SQLiteDatabase)
		 */
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ID
					+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
					+ " TEXT NOT NULL, " + KEY_DESCRIPTION + " TEXT NOT NULL, "
					+ KEY_DUE_DATE + " TEXT NOT NULL, " + KEY_DUE_TIME
					+ " TEXT NOT NULL, " + KEY_LOCATION + " TEXT NOT NULL, "
					+ KEY_CATEGORY + " TEXT NOT NULL, " + KEY_USER
					+ " TEXT NOT NULL, " + KEY_COMPLETED + " INTEGER);");
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database
		 * .sqlite.SQLiteDatabase, int, int)
		 */
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
		}
	}

	/**
	 * Creates an adapter
	 * 
	 * @param c
	 *            - context for the adapter
	 */
	public TaskDataBaseAdapter(Context c) {
		ourContext = c;
	}

	/**
	 * Opens the database for writing.
	 * 
	 * @return
	 */
	public TaskDataBaseAdapter openToWrite()
			throws android.database.SQLException {
		ourHelper = new DbHelper(ourContext);
		ourDatabase = ourHelper.getWritableDatabase();
		return this;
	}

	/**
	 * Closes the database.
	 */
	public void close() {
		ourHelper.close();
	}

	/**
	 * inserts a task into the database
	 * 
	 * @param name
	 *            task name
	 * @param description
	 *            description of the task
	 * @param dueDate
	 *            date when the task is due
	 * @param dueTime
	 *            time when the task is due
	 * @param location
	 *            where the task takes place
	 * @param category
	 *            task category
	 * @param user
	 *            user who created the task
	 * @return
	 */
	public long insert(String name, String description, String dueDate,
			String dueTime, String location, String category, String user) {

		ContentValues contentValues = new ContentValues();
		contentValues.put(KEY_NAME, name);
		contentValues.put(KEY_DESCRIPTION, description);
		contentValues.put(KEY_DUE_DATE, dueDate);
		contentValues.put(KEY_DUE_TIME, dueTime);
		contentValues.put(KEY_LOCATION, location);
		contentValues.put(KEY_CATEGORY, category);
		contentValues.put(KEY_USER, user);
		contentValues.put(KEY_COMPLETED, 0);

		Log.i(TAG, "User " + user + " inserted task: " + name + ".");

		return ourDatabase.insert(DATABASE_TABLE, null, contentValues);
	}

	/**
	 * deletes all tasks
	 * 
	 * @return pointer to database
	 */
	public int deleteAll() {
		return ourDatabase.delete(DATABASE_TABLE, null, null);
	}

	/**
	 * When is this used????
	 * 
	 * @return a string containing all of the information
	 */
	public String getData() {

		String[] columns = new String[] { KEY_ID, KEY_NAME, KEY_DESCRIPTION,
				KEY_DUE_DATE, KEY_DUE_TIME, KEY_LOCATION, KEY_CATEGORY,
				KEY_USER, KEY_COMPLETED };

		Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null,
				null, null, null);

		String result = " ";

		int iRow = cursor.getColumnIndex(KEY_ID);
		int iName = cursor.getColumnIndex(KEY_NAME);
		int iDesc = cursor.getColumnIndex(KEY_DESCRIPTION);
		int iDueDate = cursor.getColumnIndex(KEY_DUE_DATE);
		int iDueTime = cursor.getColumnIndex(KEY_DUE_TIME);
		int iLoc = cursor.getColumnIndex(KEY_LOCATION);
		int iCate = cursor.getColumnIndex(KEY_CATEGORY);
		int iUser = cursor.getColumnIndex(KEY_USER);
		int iComp = cursor.getColumnIndex(KEY_COMPLETED);

		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

			result = result + cursor.getString(iRow) + " "
					+ cursor.getString(iName) + " " + cursor.getString(iDesc)
					+ " " + cursor.getString(iDueDate) + " "
					+ cursor.getString(iDueTime) + " " + cursor.getString(iLoc)
					+ " " + cursor.getString(iCate) + " "
					+ cursor.getString(iUser) + " ";
					
			if(cursor.getString(iComp).equals("O")) result+= "COMPLETE";
			
			result+= "\n";
		}

		return result;
	}

	/**
	 * Returns 0 or 1 depending on if task if checked complete
	 * @param task_name - name of the task we are checking completeness of
	 * @return return integer 0 or 1 depending on if task if checked complete- 0=not complete, 1=complete
	 */
	public int getCompleteness(String task_name){
		ArrayList<String> detlist= getTaskDetails(task_name);
		return Integer.parseInt(detlist.get(5));
	}
	
	/**
	 * SLIGHTLY NOT FINISHED (can someone further describe what is returned)
	 * Switches the value of complete between 0 and 1
	 * This method gets an INT from getCompleteness and compares it before switching
	 * @return the updated database
	 */
	public int switchCompleteness(String task_name, String user){
		String[] columns = new String[] { KEY_ID, KEY_NAME, KEY_DESCRIPTION,
				KEY_DUE_DATE, KEY_DUE_TIME, KEY_LOCATION, KEY_CATEGORY,
				KEY_USER, KEY_COMPLETED };
		Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null,
				null, null, null);
		
		ContentValues values = new ContentValues();
		if(getCompleteness(task_name)==0){
	    	values.put(KEY_COMPLETED, 1);
	    }
	    else if(getCompleteness(task_name)==1){
	    	values.put(KEY_COMPLETED, 0);
	    }
		
		
		int iName = cursor.getColumnIndex(KEY_NAME);
		int iUser = cursor.getColumnIndex(KEY_USER);
		long rowID=0;

		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) 
		{
			if (cursor.getString(iUser).equals(user)) 
			{// this user made this	
				if(cursor.getString(iName).equals(task_name))
				{//the task matches the one being looked to change
					rowID=cursor.getInt(0);
				}	
			}
		}
		
		String where = KEY_ID+"="+rowID;
		
		return ourDatabase.update(DATABASE_TABLE, values, where,
	            null);
		
		/**
		 //The old contents of this method
	    ContentValues values = new ContentValues();
	    if(getCompleteness(task_name)==0){
	    	values.put(KEY_COMPLETED, 1);
	    }
	    else if(getCompleteness(task_name)==1){
	    	values.put(KEY_COMPLETED, 0);
	    }
	    // updating row
	    return ourDatabase.update(DATABASE_TABLE, values, null,
	            null);**/
	}
	
	
	/**
	 * Gets the names of the task for the selected user
	 * 
	 * @param user
	 *            user who made the task
	 * @return arraylist of task names
	 */
	/**
	 * @param user
	 * @return
	 */
	public ArrayList<String> getTaskNames(String user) {

		String[] columns = new String[] { KEY_ID, KEY_NAME, KEY_DESCRIPTION,
				KEY_DUE_DATE, KEY_DUE_TIME, KEY_LOCATION, KEY_CATEGORY,
				KEY_USER, KEY_COMPLETED };

		Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null,
				null, null, null);

		ArrayList<String> taskList = new ArrayList<String>();
		String task = "";

		int iName = cursor.getColumnIndex(KEY_NAME);
		int iUser = cursor.getColumnIndex(KEY_USER);

		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			// Log.i(TAG, "Get usernames for looped " + x + " times.");

			if (cursor.getString(iUser).equals(user)) {// this user made the
														// task
				task = cursor.getString(iName);
				taskList.add(task);
			}
			
		}

		return taskList;
	}

	/**
	 * Gets the names of the tasks that are completed
	 * 
	 * @param user user who created the task
	 * @return an arraylist of the names of the completed tasks
	 */
	public ArrayList<String> getCompletedTasks(String user) {

		String[] columns = new String[] { KEY_ID, KEY_NAME, KEY_DESCRIPTION,
				KEY_DUE_DATE, KEY_DUE_TIME, KEY_LOCATION, KEY_CATEGORY,
				KEY_USER, KEY_COMPLETED };

		Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null,
				null, null, null);

		ArrayList<String> taskList = new ArrayList<String>();
		String task = "";

		int iName = cursor.getColumnIndex(KEY_NAME);
		int iUser = cursor.getColumnIndex(KEY_USER);
		int iComp = cursor.getColumnIndex(KEY_COMPLETED);

		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			// Log.i(TAG, "Get usernames for looped " + x + " times.");

			if (cursor.getString(iUser).equals(user)) {// this user made the
														// task

				if (cursor.getInt(iComp) == 1) {// this user made the
					// task
					task = cursor.getString(iName);
					taskList.add(task);
				}

			}
			
		}

		return taskList;
	}

	/**
	 * Gets the names of the uncompleted tasks
	 * @param user user who created the task
	 * @return an arraylist of the names of the uncompleted tasks
	 */
	public ArrayList<String> getUnCompletedTasks(String user) {

		String[] columns = new String[] { KEY_ID, KEY_NAME, KEY_DESCRIPTION,
				KEY_DUE_DATE, KEY_DUE_TIME, KEY_LOCATION, KEY_CATEGORY,
				KEY_USER, KEY_COMPLETED };

		Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null,
				null, null, null);

		ArrayList<String> taskList = new ArrayList<String>();
		String task = "";

		int iName = cursor.getColumnIndex(KEY_NAME);
		int iUser = cursor.getColumnIndex(KEY_USER);
		int iComp = cursor.getColumnIndex(KEY_COMPLETED);

		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			// Log.i(TAG, "Get usernames for looped " + x + " times.");

			if (cursor.getString(iUser).equals(user)) {// this user made the
														// task

				if (cursor.getInt(iComp) == 0) {// this user made the
					// task
					task = cursor.getString(iName);
					taskList.add(task);
				}

			}
			
		}

		return taskList;
	}

	/**
	 * Returns task details in an arraylist
	 * @param task_name
	 * @return an arraylist of strings containing the information for that task
	 */
	public ArrayList<String> getTaskDetails(String task_name) {

		// update so that each data section is in a different cell

		String[] columns = new String[] { KEY_ID, KEY_NAME, KEY_DESCRIPTION,
				KEY_DUE_DATE, KEY_DUE_TIME, KEY_LOCATION, KEY_CATEGORY,
				KEY_USER, KEY_COMPLETED };

		Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null,
				null, null, null);

		ArrayList<String> taskDetails = new ArrayList<String>();

		int iName = cursor.getColumnIndex(KEY_NAME);
		int iDesc = cursor.getColumnIndex(KEY_DESCRIPTION);
		int iDueDate = cursor.getColumnIndex(KEY_DUE_DATE);
		int iDueTime = cursor.getColumnIndex(KEY_DUE_TIME);
		int iLoc = cursor.getColumnIndex(KEY_LOCATION);
		int iCate = cursor.getColumnIndex(KEY_CATEGORY);
		int iComp= cursor.getColumnIndex(KEY_COMPLETED);

		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			// Log.i(TAG, "Get usernames for looped " + x + " times.");

			if (cursor.getString(iName).equals(task_name)) {// this user made
															// the task
				taskDetails.add(cursor.getString(iDesc));
				taskDetails.add(cursor.getString(iDueDate));
				taskDetails.add(cursor.getString(iDueTime));
				taskDetails.add(cursor.getString(iLoc));
				taskDetails.add(cursor.getString(iCate));
				//get the completeness int, change to Integer, change to String, add to list
				taskDetails.add(((Integer)(cursor.getInt(iComp))).toString());
			}

		}
		return taskDetails;
	}
	
	/**
	 * Pulls the tasks with the same category requested.
	 * @param user The user with the tasks.
	 * @param category_name The category requested.
	 * @return List of the tasks.
	 */
	public ArrayList<String> getTasksByCategory(String user, String category_name) {

		String[] columns = new String[] { KEY_ID, KEY_NAME, KEY_DESCRIPTION,
				KEY_DUE_DATE, KEY_DUE_TIME, KEY_LOCATION, KEY_CATEGORY, KEY_USER, KEY_COMPLETED };

		Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null,
				null, null, null);

		ArrayList<String> taskList = new ArrayList<String>();
		String task = "";

		int iName = cursor.getColumnIndex(KEY_NAME);
		int iUser = cursor.getColumnIndex(KEY_USER);
		int iCategory = cursor.getColumnIndex(KEY_CATEGORY);

		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			// Log.i(TAG, "Get usernames for looped " + x + " times.");

			if (cursor.getString(iUser).equals(user)) {// this user made the task
				if (cursor.getString(iCategory).equalsIgnoreCase(category_name)) { // this is the category
					task = cursor.getString(iName);
					taskList.add(task);
				}
			}
		}

		return taskList;
	}
	
	/**
	 * This method creates a list of task names that come strictly after the provided date. Assumes date format of #/#/#
	 * 
	 * @param user The user whose tasks are being sorted
	 * @param date The after date to sort by
	 * @return A list of task names for tasks coming after the provided date.
	 */
	public ArrayList<String> getTasksByDate(String user, String date) {

		String[] columns = new String[] { KEY_ID, KEY_NAME, KEY_DESCRIPTION,
				KEY_DUE_DATE, KEY_DUE_TIME, KEY_LOCATION, KEY_CATEGORY, KEY_USER, KEY_COMPLETED };

		Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null,
				null, null, null);

		ArrayList<String> taskList = new ArrayList<String>();
		String task = "";

		int iName = cursor.getColumnIndex(KEY_NAME);
		int iUser = cursor.getColumnIndex(KEY_USER);
		int iDate = cursor.getColumnIndex(KEY_DUE_DATE);
		
		Scanner scan = new Scanner (date);
		int user_day, prov_day = 0, user_month, prov_month, user_year, prov_year = 0;
		
		scan.useDelimiter("/");
		if(scan.hasNext())
		{	
			String sub = scan.next();
			prov_month = Integer.parseInt(sub);
			if(scan.hasNext())
			{
				sub = scan.next();
				prov_day = Integer.parseInt(sub);
				if(scan.hasNext())
				{
					sub = scan.next();
					prov_year = Integer.parseInt(sub);
				}
			}
		
		
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
				// Log.i(TAG, "Get usernames for looped " + x + " times.");
				Scanner other = new Scanner (cursor.getString(iDate));
				other.useDelimiter("/");
				sub = other.next();
				user_month = Integer.parseInt(sub);
				sub = other.next();
				user_day = Integer.parseInt(sub);
				sub = other.next();
				user_year = Integer.parseInt(sub);

				if (cursor.getString(iUser).equals(user)) {// this user made the task
					if (user_year == prov_year) { //The provided year equals the date's year
						if(user_month==prov_month){//The provided month equals the date's month
							if(user_day>prov_day){//The date is after the provided date
								task = cursor.getString(iName);
								taskList.add(task);
							}
						}
						else if(user_month>prov_month){//The date is after the provided date
							task = cursor.getString(iName);
							taskList.add(task);
						}
					}
					else if(user_year>prov_year){//The date is after the provided date
						task = cursor.getString(iName);
						taskList.add(task);
					}
				}
			}
		}
		return taskList;
	}
	
	public SQLiteDatabase getOurDatabase() {
		return ourDatabase;
	}

}
